# 心知天气API方法实现

def _get_current_weather_seniverse(self):
    """
    从心知天气API获取当前天气数据
    """
    if not self.seniverse_key:
        print("缺少心知天气API密钥")
        return None
    
    base_url = DATA_CONFIG['api']['seniverse']['base_url']
    language = DATA_CONFIG['api']['seniverse']['language']
    unit = DATA_CONFIG['api']['seniverse']['unit']
    
    all_data = []
    
    for city in self.cities:
        try:
            # 心知天气API使用城市名称查询
            url = f"{base_url}weather/now.json?key={self.seniverse_key}&location={city['name']}&language={language}&unit={unit}"
            response = requests.get(url)
            
            if response.status_code == 200:
                data = response.json()
                
                # 提取需要的数据
                weather_data = {
                    'city': city['name'],
                    'city_id': city['id'],
                    'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    'temp': data['results'][0]['now']['temperature'],
                    'humidity': data['results'][0]['now']['humidity'],
                    'wind_speed': data['results'][0]['now']['wind_speed'],
                    'wind_direction': data['results'][0]['now']['wind_direction'],
                    'weather_condition': data['results'][0]['now']['text'],
                    'data_source': 'seniverse'
                }
                
                all_data.append(weather_data)
                print(f"成功获取 {city['name']} 的当前天气数据")
            else:
                print(f"获取 {city['name']} 的天气数据失败: {response.status_code} - {response.text}")
        
        except Exception as e:
            print(f"获取 {city['name']} 的天气数据时出错: {e}")
        
        # 添加延迟，避免API请求过于频繁
        time.sleep(1)
    
    if all_data:
        # 转换为DataFrame
        df = pd.DataFrame(all_data)
        
        # 保存为CSV
        output_path = os.path.join(self.raw_data_path, 'current_weather_raw.csv')
        df.to_csv(output_path, index=False)
        print(f"当前天气数据已保存至: {output_path}")
        
        return df
    else:
        print("未获取到任何天气数据")
        return None

def _get_forecast_seniverse(self, days=3):
    """
    从心知天气API获取天气预报数据
    """
    if not self.seniverse_key:
        print("缺少心知天气API密钥")
        return None
    
    base_url = DATA_CONFIG['api']['seniverse']['base_url']
    language = DATA_CONFIG['api']['seniverse']['language']
    unit = DATA_CONFIG['api']['seniverse']['unit']
    
    # 确保天数在API限制范围内
    days = min(days, 3)  # 心知天气免费版最多3天
    
    all_data = []
    
    for city in self.cities:
        try:
            url = f"{base_url}weather/daily.json?key={self.seniverse_key}&location={city['name']}&language={language}&unit={unit}&days={days}"
            response = requests.get(url)
            
            if response.status_code == 200:
                data = response.json()
                
                # 提取预报数据
                for day in data['results'][0]['daily']:
                    forecast_date = day['date']
                    
                    # 每日预报
                    day_forecast = {
                        'city': city['name'],
                        'city_id': city['id'],
                        'forecast_time': f"{forecast_date} 00:00:00",
                        'temp': (float(day['high']) + float(day['low'])) / 2,  # 平均温度
                        'temp_min': day['low'],
                        'temp_max': day['high'],
                        'humidity': day.get('humidity', ''),  # 心知天气可能不提供湿度
                        'wind_speed': day['wind_speed'],
                        'wind_direction': day['wind_direction'],
                        'weather_condition': day['text_day'],
                        'data_source': 'seniverse',
                        'forecast_type': 'daily'
                    }
                    
                    all_data.append(day_forecast)
                
                print(f"成功获取 {city['name']} 的天气预报数据")
            else:
                print(f"获取 {city['name']} 的天气预报失败: {response.status_code} - {response.text}")
        
        except Exception as e:
            print(f"获取 {city['name']} 的天气预报时出错: {e}")
        
        # 添加延迟，避免API请求过于频繁
        time.sleep(1)
    
    if all_data:
        # 转换为DataFrame
        df = pd.DataFrame(all_data)
        
        # 保存为CSV
        output_path = os.path.join(self.raw_data_path, 'weather_forecast_raw.csv')
        df.to_csv(output_path, index=False)
        print(f"天气预报数据已保存至: {output_path}")
        
        return df
    else:
        print("未获取到任何天气预报数据")
        return None